package com.yibo.message.Helper;

import com.yibo.db.message.entity.EmailServerEntity;
import com.yibo.db.user.entity.User;
import com.yibo.message.core.EmailMessage;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * 发送邮件
 */
public final class SendEmail {

    private static Properties  mailProp(EmailServerEntity emailServerEntity){
        Properties prop = new Properties();
        //协议
        prop.setProperty("mail.transport.protocol", "smtp");
        //主机名
        prop.setProperty("mail.smtp.host", emailServerEntity.getHost());
        //是否开启权限控制
        prop.setProperty("mail.smtp.auth", "true");
        //返回发送的cmd源码
        prop.setProperty("mail.debug", "true");
        //端口
        prop.setProperty("mail.smtp.port",emailServerEntity.getPort()+"");
        return prop;
    }

    public static void send(EmailServerEntity emailServerEntity, EmailMessage emailMessage){
        Properties prop = mailProp(emailServerEntity);
        Session session = Session.getInstance(prop);
        Message msg = new MimeMessage(session);
        new Thread(()->{
            int times = 0;
            while(true) {
                try {
                    msg.setFrom(new InternetAddress(emailServerEntity.getUserName()));
                    //抄送自己
                    msg.setRecipient(MimeMessage.RecipientType.CC, new InternetAddress(emailServerEntity.getUserName()));
                    // 要发送的email，可以设置数组
                    msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(emailMessage.getEmail()));
                    //邮件标题
                    msg.setSubject(emailMessage.getTitle());
                    //邮件正文
                    msg.setText(emailMessage.getMessage());
                    msg.saveChanges();
                    //不被当作垃圾邮件的关键代码--Begin ，如果不加这些代码，发送的邮件会自动进入对方的垃圾邮件列表
                    msg.addHeader("X-Priority", "3");
                    msg.addHeader("X-MSMail-Priority", "Normal");
                    //本文以outlook名义发送邮件，不会被当作垃圾邮件
                    msg.addHeader("X-Mailer", "Microsoft Outlook Express 6.00.2900.2869");
                    msg.addHeader("X-MimeOLE", "Produced By Microsoft MimeOLE V6.00.2900.2869");
                    msg.addHeader("ReturnReceipt", "1");
                    //不被当作垃圾邮件的关键代码--end
                    Transport trans = session.getTransport("smtp");
                    trans.connect(emailServerEntity.getHost(), emailServerEntity.getUserName(), emailServerEntity.getPassword()); // 邮件的账号密码
                    trans.sendMessage(msg, msg.getAllRecipients());
                    break;
                } catch (Exception e) {
                    //此处拒绝抛出异常
                    times++;
                    if(times > 5){
                        break;
                    }
                }
            }
        }).start();
    }
}
